import router, { resetRouter } from "./router"
import store from "./store"
// import { Message } from 'element-ui';
import NProgress from "nprogress" // progress bar
import "nprogress/nprogress.css" // progress bar style
import { getToken } from '@/utils/auth'; // get token from cookie
import getPageTitle from "@/utils/get-page-title"

NProgress.configure({showSpinner: false}) // NProgress Configuration

const whiteList = ["/login"] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  if (getToken()) {
    if (to.path === "/login") {
      next({path: "/"})
      NProgress.done()
    } else {
      if (store.getters.routeLen == 3) {
        resetRouter()
        const accessRoutes = await store.dispatch("permission/generateRoutes", store.getters.roleCode)
        router.addRoutes(accessRoutes) // 动态添加可访问路由表
        next({...to, replace: true}) // hack方法 确保addRoutes已完成
      } else {
        next()
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      if (sessionStorage.getItem('projectRef')) {
        next(`/login?projectRef=${sessionStorage.getItem('projectRef')}`) // 否则全部重定向到登录页
      } else {
        next(`/login`) // 否则全部重定向到登录页
      }

      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
